import _ from "lodash";
import service from "@service";
import { usersLogin } from "@/service/api.js"
import { mainMenu, getMenuList } from "@/mock/menu.js";

import { getSign, getMenuByRoute } from "@utils";
import { MOUDLE_MAP } from "@constants"

import {
    transArrayToTree,
    traversalTree,
    renameTreeField,
} from "@utils/dataStruct";
import { getTokenInfo, setSessionCookie, clearOutSizeSession } from "@utils/session";

export default {
    namespaced: true,
    state: {
        accountObject: null,
        menuList: null,
        menuMap: {},
        buttonList: null,
        buttonAuth: {},
        activePath: [],
        homePage: {
            name: "首页",
            key: "main",
            type: "menu",
            description: "<%frontName--main%>",
            menuIconType: "s-home",
        },
        termAccount: null,
        initDone: false, // 是否初始化成功
    },
    mutations: {
        SET_ACCOUNT(state, info) {
            state.accountObject = info;
        },
        SET_INITDONE(state, info) {
            state.initDone = info;
        },
        SET_MENU(state, info) {
            state.menuList = info;
            localStorage.setItem(
                "menuList",
                JSON.stringify(info)
            );
            if (info) {
                // 塞进去一个首页
                state.menuMap=[]
                // info.unshift(state.homePage)
                traversalTree(info, (item) => {
                    state.menuMap[item.key] = item;
                });


            }
        },
        SET_BUTTON(state, payload) {
            state.buttonList = payload;
            let obj = {};
            payload?.forEach((item) => {
                obj[item.ELEMENTURL] = item;
            })
            state.buttonAuth = obj;
        },
        SET_ACTIVE_PATH(state, payload) {
            state.activePath = payload;
        },
        SET_TERM_ACCOUNT(state, payload) {
            state.termAccount = payload;
        }
    },
    actions: {
        async init({ state, commit, dispatch, rootState }, params) {
            let tokenInfo = getTokenInfo();

            if (!tokenInfo) {
                return;
            }
            let authQryAuthTree

            try {
                // use info
                let userInfo = JSON.parse(sessionStorage.getItem("userInfo"));

                commit("SET_ACCOUNT", userInfo);

                let buttonList = [];

                let menuList = getMenuList(userInfo.permissionIds)// mainMenu;

                commit("SET_MENU", menuList);
                commit("SET_BUTTON", buttonList);

                // }
            } catch (error) {
                console.log("init error", error);
                await dispatch("logout");
            }
            commit("SET_INITDONE", true);
            return { authQryAuthTree }
        },
        async login({ state, dispatch,commit }, params) {
            let result = null;
            result = await usersLogin(params.data)
            console.log("result", result);
            if (result) {
                let token = {
                    ...result.data,
                    access_token: new Date().getTime(),
                    staffId: result?.data?.id,
                    staffName: result?.data?.userName,
                    // todo 测试
                    // "permissionIds": [
                    //     "patientManage",
                    //     "visitManage",
                    //     "diagnosisDict",
                    //     "orderItemDict"
                    // ]
                }

                setSessionCookie(JSON.stringify(token));

                // 记录一个token更新时间时间
                // setSessionCookie(new Date().getTime(), {
                //     cookieFieldName: 'tokenTime',
                // });

                sessionStorage.setItem("userInfo", JSON.stringify(token));
            }

            //初始化结果
            let init = await dispatch("init");

            return { result ,init};
        },
        async logout({ state, dispatch, commit }, params) {

            setSessionCookie();

            commit("SET_ACCOUNT", null);
            commit("SET_MENU", null);
            commit("SET_BUTTON", null);
            commit('SET_ACTIVE_PATH', []);

            // 清理三方登录信息
            clearOutSizeSession()

            g_instance.$router.push("/login", {
                query: {}, // 手动退出登录，登陆后不跳回之前页面
            });

            return result;
        },
        setMenuByRoute({ state, dispatch, commit }, route) {
            let pathList = getMenuByRoute(route, state.menuList);
            if (pathList && pathList[0]) {
                commit('SET_ACTIVE_PATH', pathList[0]);
            }
        },
    },
    getters: {
        staffName: function (state) {
            return _.get(state, "accountObject.staffName");
        },
        getPermissionJudgeHandle(state) {
            return permissionName => {
                let buttonList = state.buttonList || [];

                return (
                    buttonList &&
                    buttonList.some(v => {
                        return v.ELEMENTURL === permissionName;
                    })
                );
            };
        }
    },
};
